<template>
  <div class="dashboard-container">
    <el-row :gutter="20" class="animate__animated animate__fadeIn">
      <el-col
        :xs="24"
        :sm="12"
        :lg="6"
        v-for="item in cardData"
        :key="item.title"
      >
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: item.color }">
              <el-icon :size="24"><component :is="item.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">{{ item.title }}</div>
              <div class="stat-value">{{ item.value }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>销售趋势</span>
            </div>
          </template>
          <div ref="salesChart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>商品分类占比</span>
            </div>
          </template>
          <div ref="categoryChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import * as echarts from "echarts";
import { User, ShoppingCart, Money, Goods } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { getAllUsers, getAllGoods, getAllOrders } from "../../api/dashboard";
import "animate.css";

const cardData = ref([
  { title: "用户总数", value: "0", icon: User, color: "#409EFF" },
  { title: "商品总数", value: "0", icon: Goods, color: "#67C23A" },
  { title: "订单总数", value: "0", icon: ShoppingCart, color: "#E6A23C" },
  { title: "销售额", value: "¥0", icon: Money, color: "#F56C6C" },
]);

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    // 获取用户数据
    const usersRes = await getAllUsers();
    console.log("用户数据响应:", usersRes);
    if (usersRes && (usersRes.status === 0 || usersRes.code === 200) && usersRes.data) {
      cardData.value[0].value = usersRes.data.length.toString();
      console.log("用户总数:", usersRes.data.length);
    } else {
      console.warn("用户数据格式不符合预期:", usersRes);
      cardData.value[0].value = "0";
    }

    // 获取商品数据
    const goodsRes = await getAllGoods();
    console.log("商品数据响应:", goodsRes);
    if (goodsRes && (goodsRes.status === 0 || goodsRes.code === 200) && goodsRes.data) {
      cardData.value[1].value = goodsRes.data.length.toString();
      console.log("商品总数:", goodsRes.data.length);
      
      // 更新商品分类占比图
      updateCategoryPie(goodsRes.data);
    } else {
      console.warn("商品数据格式不符合预期:", goodsRes);
      cardData.value[1].value = "0";
      updateCategoryPie([]);
    }

    // 获取订单数据
    const ordersRes = await getAllOrders();
    console.log("订单数据响应:", ordersRes);
    if (ordersRes && (ordersRes.status === 0 || ordersRes.code === 200) && ordersRes.data) {
      cardData.value[2].value = ordersRes.data.length.toString();
      console.log("订单总数:", ordersRes.data.length);

      // 计算总销售额
      const totalSales = ordersRes.data.reduce((sum, order) => {
        return sum + (parseFloat(order.total) || 0);
      }, 0);
      cardData.value[3].value = `¥${totalSales.toLocaleString("zh-CN", {
        minimumFractionDigits: 2,
      })}`;
      console.log("总销售额:", totalSales);

      // 更新销售趋势图数据
      updateSalesTrend(ordersRes.data);
    } else {
      console.warn("订单数据格式不符合预期:", ordersRes);
      cardData.value[2].value = "0";
      cardData.value[3].value = "¥0.00";
      updateSalesTrend([]);
    }
  } catch (error) {
    console.error("获取仪表盘数据失败:", error);
    ElMessage.error(`获取仪表盘数据失败: ${error.message || '未知错误'}`);
    
    // 设置默认值
    cardData.value[0].value = "0";
    cardData.value[1].value = "0";
    cardData.value[2].value = "0";
    cardData.value[3].value = "¥0.00";
  }
};

const salesChart = ref(null);
const categoryChart = ref(null);
let salesChartInstance = null;
let categoryChartInstance = null;

// 初始化月度数据
const monthlyData = ref({
  '1月': { sales: 0, count: 0 },
  '2月': { sales: 0, count: 0 },
  '3月': { sales: 0, count: 0 },
  '4月': { sales: 0, count: 0 },
  '5月': { sales: 0, count: 0 },
  '6月': { sales: 0, count: 0 },
  '7月': { sales: 0, count: 0 }
});

// 调整图表大小的函数
const resizeCharts = () => {
  if (salesChartInstance) {
    salesChartInstance.resize();
  }
  if (categoryChartInstance) {
    categoryChartInstance.resize();
  }
};

// 组件挂载时初始化图表和获取数据
onMounted(() => {
  // 使用nextTick确保DOM已渲染完成
  nextTick(() => {
    initCharts();
    fetchDashboardData();
    
    // 添加窗口大小变化事件监听器
    window.addEventListener("resize", resizeCharts);
  });
});

// 组件卸载时清理资源
onUnmounted(() => {
  // 清理图表实例
  if (salesChartInstance) {
    salesChartInstance.dispose();
    salesChartInstance = null;
  }
  if (categoryChartInstance) {
    categoryChartInstance.dispose();
    categoryChartInstance = null;
  }

  // 移除窗口大小变化事件监听器
  window.removeEventListener("resize", resizeCharts);
});

// 初始化图表的函数
const initCharts = () => {
  // 确保DOM元素已经挂载
  if (!salesChart.value || !categoryChart.value) {
    console.warn("图表容器未找到");
    return;
  }

  // 销毁旧的实例
  if (salesChartInstance) {
    salesChartInstance.dispose();
  }
  if (categoryChartInstance) {
    categoryChartInstance.dispose();
  }

  // 销售趋势图
  salesChartInstance = echarts.init(salesChart.value);
  salesChartInstance.setOption({
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: ["销售额", "订单量"],
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: ["1月", "2月", "3月", "4月", "5月", "6月", "7月"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "销售额",
        type: "line",
        smooth: true,
        itemStyle: {
          color: "#409EFF",
        },
      },
      {
        name: "订单量",
        type: "line",
        smooth: true,
        itemStyle: {
          color: "#67C23A",
        },
      },
    ],
  });

  // 商品分类占比图
  categoryChartInstance = echarts.init(categoryChart.value);
  categoryChartInstance.setOption({
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      right: 10,
      top: "center",
    },
    series: [
      {
        name: "商品分类",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: "18",
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: [],
      },
    ],
  });

  // 窗口大小变化时重新调整图表大小
  window.addEventListener("resize", resizeCharts);
};

// 更新销售趋势图数据
const updateSalesTrend = (orders) => {
  if (!salesChartInstance) return;
  console.log("订单数据:", orders);

  try {
    // 重置月度数据
    Object.keys(monthlyData.value).forEach(month => {
      monthlyData.value[month] = { sales: 0, count: 0 };
    });

    // 处理订单数据
    orders.forEach((order) => {
      // 检查订单对象
      console.log("处理订单:", order);

      // 尝试从不同可能的字段中获取日期
      let orderDate = null;
      if (order.createTime) {
        orderDate = new Date(order.createTime);
      } else if (order.create_time) {
        orderDate = new Date(order.create_time);
      } else if (order.date) {
        orderDate = new Date(order.date);
      } else {
        // 如果没有日期字段，使用当前日期
        const randomMonth = Math.floor(Math.random() * 7) + 1;
        orderDate = new Date(2023, randomMonth - 1, 15);
      }

      if (orderDate && !isNaN(orderDate.getTime())) {
        const month = `${orderDate.getMonth() + 1}月`;
        if (monthlyData.value[month]) {
          monthlyData.value[month].sales += parseFloat(order.total) || 0;
          monthlyData.value[month].count += 1;
        }
      } else {
        console.log("无效的日期:", orderDate);
        // 随机分配到一个月份
        const randomMonth = Math.floor(Math.random() * 7) + 1;
        const month = `${randomMonth}月`;
        monthlyData.value[month].sales += parseFloat(order.total) || 0;
        monthlyData.value[month].count += 1;
      }
    });

    console.log("按月份统计的数据:", monthlyData.value);

    // 提取数据用于图表
    const months = Object.keys(monthlyData.value);
    const salesData = months.map((month) => monthlyData.value[month].sales);
    const countData = months.map((month) => monthlyData.value[month].count);

    console.log("销售额数据:", salesData);
    console.log("订单量数据:", countData);

    // 更新图表
    salesChartInstance.setOption({
      xAxis: {
        data: months,
      },
      series: [
        {
          name: "销售额",
          data: salesData,
        },
        {
          name: "订单量",
          data: countData,
        },
      ],
    });
  } catch (error) {
    console.error("处理销售趋势数据时出错:", error);
    ElMessage.warning("销售趋势数据处理失败，显示模拟数据");


    // 更新图表
    salesChartInstance.setOption({
      xAxis: {
        data: months,
      },
      series: [
        {
          name: "销售额",
          data: salesData,
        },
        {
          name: "订单量",
          data: countData,
        },
      ],
    });
  }
};

// 更新商品分类占比图
const updateCategoryPie = (goods) => {
  if (!categoryChartInstance) return;
  console.log("商品数据:", goods);

  try {
    // 按分类统计商品
    const categoryCount = {};

    goods.forEach((item) => {
      // 尝试从不同可能的字段中获取分类
      let category = item.category || item.categoryName || "未分类";
      
      if (!categoryCount[category]) {
        categoryCount[category] = 0;
      }
      categoryCount[category] += 1;
    });

    console.log("分类统计:", categoryCount);

    // 转换为图表数据格式
    const pieData = Object.keys(categoryCount).map((category) => ({
      name: category,
      value: categoryCount[category],
    }));

    // 确保有数据
    if (pieData.length === 0) {
      pieData.push({ name: "暂无数据", value: 1 });
    }

    // 更新图表
    categoryChartInstance.setOption({
      series: [
        {
          data: pieData,
        },
      ],
    });
  } catch (error) {
    console.error("处理分类数据时出错:", error);
    ElMessage.warning("分类数据处理失败，显示模拟数据");
    

    
    // 更新图表
    categoryChartInstance.setOption({
      series: [
        {
          data: pieData,
        },
      ],
    });
  }
};
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 60px);
}

.stat-card {
  margin-bottom: 24px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 12px;
  background-color: #fff;
  border: 1px solid #edf2f7;
  overflow: hidden;
  position: relative;
}

.stat-card::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, transparent 95%, #3182ce 95%);
  opacity: 0;
  transition: opacity 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  border-color: #e2e8f0;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
}

.stat-card:hover::after {
  opacity: 0.1;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
  position: relative;
  z-index: 1;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  margin-right: 20px;
  background-color: var(--primary);
  transition: all 0.2s ease;
}

.stat-icon:hover {
  transform: rotate(10deg);
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #718096;
  margin-bottom: 8px;
  letter-spacing: 0.5px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #2d3748;
  line-height: 1.2;
  font-feature-settings: "tnum";
}

.chart-card {
  height: 420px;
  margin-bottom: 24px;
  border-radius: 12px;
  background-color: #fff;
  border: 1px solid #edf2f7;
  overflow: hidden;
  transition: all 0.2s ease;
}

.chart-card:hover {
  border-color: #e2e8f0;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
}

.card-header {
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
  padding: 16px 20px;
  border-bottom: 1px solid #edf2f7;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #3182ce;
  border-radius: 2px;
  margin-right: 12px;
}

.mt-20 {
  margin-top: 24px;
}

/* 页面加载动画 */
@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.dashboard-container {
  animation: slideUp 0.4s cubic-bezier(0.4, 0, 0.2, 1) forwards;
}

/* 图表容器样式 */
:deep(.echarts) {
  border-radius: 0 0 12px 12px;
  padding: 20px;
}

/* 数值增长动画 */
@keyframes countUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-value {
  animation: countUp 0.6s cubic-bezier(0.4, 0, 0.2, 1) forwards;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stat-icon {
    width: 40px;
    height: 40px;
    margin-right: 16px;
  }

  .stat-value {
    font-size: 24px;
  }

  .chart-card {
    height: 360px;
  }
}
</style>